<script>
/* 
    上传一张图片页面
 */
import { defineComponent } from 'vue'
export default defineComponent({
	name: 'Upload'
})
</script>
<script setup>
import { ref, defineExpose } from 'vue'
import { baseConfig } from '@/config'
import { Upload, Link } from '@element-plus/icons-vue'
import { useAuth } from '@/hooks'
const { state } = useAuth()
// confi为index.js里面的根路径
const isRefresh = ref(true)
const url = ref('/wework/media/uploadfile')

const props = defineProps({
	imgurl: {
		type: String,
		default: ''
	},
	text: {
		type: String,
		default: ''
	},
	classifier: {
		type: String,
		default: 'upload'
	}
})
console.log(props.imgurl)
const imgurlRef = ref(props.imgurl)

const handleSuccess = (response, uploadFile) => {
	imgurlRef.value = URL.createObjectURL(uploadFile.raw)
	console.log(response)
	emits('getImg', response.data.url)
}

const beforeUpload = (rawFile) => {
	console.log('图片546456456', rawFile.type.indexOf('image'))
	if (rawFile.type.indexOf('image') == -1) {
		ElMessage.error('请上传图片')
		return false
	} else if (rawFile.size / 1024 / 1024 > 2) {
		ElMessage.error(' picture size can not exceed 2MB!')
		return false
	}
	return true
}
let headers = {
	'UserToken': state.token,
	// 'UserToken': '1f391c6c-51d9-11ed-8dd2-00163e2292ca',
}
const emits = defineEmits(['getImg'])
</script>
<template>
	<div>
		<el-upload
			class="uploader"
			name='file'
			:action="url"
			:headers="headers"
			:show-file-list="false"
			:on-success="handleSuccess"
			:before-upload="beforeUpload"
		>
			<img v-if="imgurlRef" :src="imgurlRef" class="upload-img" />
			<!-- <i v-else class="upload-icon el-icon-plus"></i> -->

			<div v-else class="upload-icon">
				<el-button v-if="classifier === 'upload'" class="btn-upload" :icon="Upload">上传文件</el-button>
				<el-button v-else class="btn-upload" :icon="Link">上传文件</el-button>
				<!-- <p v-if="props.text != ''" style="margin-top: 15px">{{ props.text }}</p> -->
			</div>
		</el-upload>
	</div>
</template>
<style lang="scss" scoped>
.uploader {
	margin-top: 20px;
	padding-left: 16px;
	.btn-upload {
		background: rgba(21, 132, 255, 0.16);
	}
}
.upload-img {
	width: 120px;
	height: 120px;
	display: block;
}
</style>
